<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input v-model="listQuery.dresname" style="width: 200px;" class="filter-item" placeholder="请输入危险源名称" @keyup.enter.native="handleFilter"/>
      <el-input v-model="listQuery.supervisorname" style="width: 200px;" class="filter-item" placeholder="请输入监管名称" @keyup.enter.native="handleFilter"/>
      <!--<el-input v-model="listQuery.identification" style="width: 200px;" class="filter-item" placeholder="请输入身份证" @keyup.enter.native="handleFilter"/>-->
      <el-button v-waves v-if="btn_query" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">{{ $t('table.search') }}</el-button>
      <el-button v-if="btn_add" class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">{{ $t('table.add') }}</el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      element-loading-text="给我一点时间"
      border
      fit
      highlight-current-row
      style="width: 100%">
      <el-table-column width="90" align="center" label="危险源ID">
        <template slot-scope="scope">
          <span>{{ scope.row.dresourceid }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label= "危险源名称">
        <template slot-scope="scope">
          <span>{{ scope.row.dresname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" align="center" label="监管名称">
        <template slot-scope="scope">
          <!--<span v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value">-->
          <!--<span v-if="item.value == scope.row.supervisorid">{{ item.label }}</span>-->
          <!--</span>-->
          <span>{{ scope.row.supervisorname }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="危险源类型">
        <template slot-scope="scope">
          <span v-for="item in dictList('drestype')" :key="item.value" :label="item.label" :value="item.value">
            <span v-if="item.value == scope.row.drestype">{{ item.label }}</span>
          </span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="危险级别">
        <template slot-scope="scope">
          <span v-for="item in dictList('dangrousResouceLevel')" :key="item.value" :label="item.label" :value="item.value">
            <span v-if="item.value == scope.row.level">{{ item.label }}</span>
          </span>
        </template>
      </el-table-column>
      <!--<el-table-column width="120" label="经度">
        <template slot-scope="scope">
          <span>{{ scope.row.longitude }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="纬度">
        <template slot-scope="scope">
          <span>{{ scope.row.latitude }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="高度">
        <template slot-scope="scope">
          <span>{{ scope.row.levation }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="省">
        <template slot-scope="scope">
          <span>{{ scope.row.province }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="市">
        <template slot-scope="scope">
          <span>{{ scope.row.city }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="区">
        <template slot-scope="scope">
          <span>{{ scope.row.zone }}</span>
        </template>
      </el-table-column>
      <el-table-column width="120" label="街道">
        <template slot-scope="scope">
          <span>{{ scope.row.district }}</span>
        </template>
      </el-table-column>-->
      <el-table-column width="150" align="center" label="完整地址">
        <template slot-scope="scope">
          <span>{{ scope.row.detailAddress }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="创建时间">
        <template slot-scope="scope">
          <span>{{ dformat("yyyy-MM-dd hh:mm:ss",scope.row.createtime) }}</span>
        </template>
      </el-table-column>
      <el-table-column width="100" align="center" label="更新时间">
        <template slot-scope="scope">
          <span>{{ dformat("yyyy-MM-dd hh:mm:ss",scope.row.updatetime) }}</span>
        </template>
      </el-table-column>

      <el-table-column :label="$t('table.actions')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-if="btn_edit" type="primary" size="mini" @click="handleUpdate(scope.row)">{{ $t('table.edit') }}</el-button>
          <el-button v-if="btn_delete" size="mini" type="danger" @click="handleDelete(scope.row)">{{ $t('table.delete') }}</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        :current-page.sync="listQuery.page"
        :page-sizes="[10,20,30, 50]"
        :page-size="listQuery.limit"
        :total="total"
        background
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"/>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="right" label-width="100px" style="width: 450px; margin-left:50px;">
        <el-form-item label="危险源名称" prop="dresname">
          <el-input v-model="temp.dresname"/>
        </el-form-item>
        <el-form-item label="监管名称" prop="supervisorid">
          <el-select v-model="temp.supervisorid" class="select-width-100" placeholder="请选择">
            <el-option v-for="item in supervisorOptions" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="危险源类型" prop="drestype">
          <el-select v-model="temp.drestype" class="select-width-100" placeholder="请选择">
            <el-option v-for="item in dictList('drestype')" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="危险级别" prop="level">
          <el-select v-model="temp.level" class="select-width-100" placeholder="请选择">
            <el-option v-for="item in dictList('dangrousResouceLevel')" :key="parseInt(item.value)" :label="item.label" :value="parseInt(item.value)"/>
          </el-select>
        </el-form-item>
        <div id="district">
          <span id="pczlabel">省市区</span>
          <el-select v-model="temp.province" placeholder="省级地区" @change="chooseProvince">
            <el-option
              v-for="item in provinceOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
          <el-select v-model="temp.city" placeholder="市级地区" @change="chooseCity">
            <el-option
              v-for="item in cityOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
          <el-select v-model="temp.zone" placeholder="区级地区">
            <el-option
              v-for="item in zoneOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </div>

        <!--<el-form-item label="省" prop="province">
          <el-input v-model="temp.province"/>
        </el-form-item>
        <el-form-item label="市" prop="city">
          <el-input v-model="temp.city"/>
        </el-form-item>
        <el-form-item label="区" prop="zone">
          <el-input v-model="temp.zone"/>
        </el-form-item>-->
        <el-form-item label="街道" prop="district">
          <el-input v-model="temp.district"/>
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="temp.address"/>
        </el-form-item>
        <el-form-item label="经纬度" prop="longitude">
          <div id="lola">
            <el-input v-model="temp.longitude"/>
            <el-input v-model="temp.latitude"/>
            <el-button type="primary" size="medium" @click="openMap">定位</el-button>
          </div>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('table.cancel') }}</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">{{ $t('table.confirm') }}</el-button>
        <el-button v-else type="primary" @click="updateData">{{ $t('table.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!--百度地图 外面加一层div是为了关闭el-dialog 再打开时可以重新加载el-dialog -->
    <div v-if="mapVisible">
      <el-dialog :visible.sync="mapVisible" title="定位" width="60%" @close="closeMap">
        <baidu-map
          :center="center"
          :zoom="zoom"
          :scroll-wheel-zoom="true"
          :ak="ak"
          class="map">
          <bm-marker ref="marker" :position="{lng: center.lng, lat: center.lat}" :dragging="true" @dragend="dragEndPosition"/>
          <bm-city-list ref="bmcity" anchor="BMAP_ANCHOR_TOP_LEFT" @changeAfter="changeMarker"/>
        </baidu-map>
        <div slot="footer" class="dialog-footer">
          <el-button @click="closeMap">{{ $t('table.cancel') }}</el-button>
          <el-button type="primary" @click="confirmSite">{{ $t('table.confirm') }}</el-button>
        </div>
      </el-dialog>
    </div>

  </div>
</template>

<script>
import { getDangerList, addDanger, updateDanger, deleteDanger, getProvinceOpt, getCityOrZoneOpt } from '@/api/fire/supervisor/danger'
import { selectLabelValue } from '@/api/fire/supervisor/base'
import { getAk } from '@/api/fire/map/map'
import { dateFormat } from '@/utils/dateFormatter'
import { BaiduMap, BmMarker, BmCityList } from 'vue-baidu-map'
import waves from '@/directive/waves' // 水波纹指令

export default {
  name: 'Danger',
  directives: {
    waves
  },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  components: {
    BaiduMap, // 指定组件模板
    BmMarker,
    BmCityList
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        dresname: '',
        supervisorname: ''
      },
      showReviewer: false,
      temp: {
        supervisorid: '',
        supervisorname: '',
        dresname: '',
        drestype: '',
        level: '',
        updatetime: '',
        longitude: '',
        latitude: '',
        levation: '',
        province: '',
        city: '',
        zone: '',
        district: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑危险源',
        create: '创建危险源'
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        dresname: [{ required: true, message: '请选择危险源名称', trigger: 'blur' }],
        supervisorid: [{ required: true, message: '请选择监管', trigger: 'blur' }],
        level: [{ required: true, message: '请选择危险级别', trigger: 'blur' }],
        drestype: [{ required: true, message: '请选择危险源类型', trigger: 'blur' }]
      },
      dialogFormRolesVisible: false,
      btn_query: false,
      btn_add: false,
      btn_edit: false,
      btn_delete: false,
      supervisorOptions: null,
      provinceOpt: null,
      cityOpt: null,
      zoneOpt: null,
      address: '',
      mapVisible: false,
      ak: '',
      center: { lng: 0, lat: 0 }, // 经纬度
      zoom: 12, // 地图展示级别
      de_lng: 0, // 拖拽marker后的lng
      de_lat: 0 // 拖拽marker后lat
    }
  },
  created() {
    this.getList()
    this.btn_query = this.checkPermission(['supervisor:danger:list'])
    this.btn_add = this.checkPermission(['supervisor:danger:add'])
    this.btn_edit = this.checkPermission(['supervisor:danger:update'])
    this.btn_delete = this.checkPermission(['supervisor:danger:delete'])
    this.querySupervisorOptions()
    this.queryProvinceOpt()
    // 向后台获取百度ak
    getAk().then(response => {
      this.ak = response.data.context
    })
  },
  methods: {
    openMap() {
      this.resetMap()
      this.zoom = 5
      if (this.dialogStatus === 'update') {
        // 打开时回显
        if (this.temp.longitude !== '' && this.temp.longitude !== undefined &&
          this.temp.latitude !== '' && this.temp.latitude !== undefined) {
          this.center.lng = this.temp.longitude
          this.center.lat = this.temp.latitude
          this.de_lng = this.temp.longitude
          this.de_lat = this.temp.latitude
          this.zoom = 12
        }
      }
      this.mapVisible = true
    },
    closeMap() {
      this.mapVisible = false
    },
    confirmSite() {
      // 确认时将marker中的lng,lat的值赋给temp里的longitude，latitude
      this.temp.longitude = this.de_lng
      this.temp.latitude = this.de_lat
      this.mapVisible = false
    },
    resetMap() {
      this.center.lng = 116.405419
      this.center.lat = 39.914271
      this.de_lng = 116.405419
      this.de_lat = 39.914271
    },
    changeMarker() {
      // 选择城市以后将marker转移
      this.center.lng = this.$refs.bmcity.map.Oe.lng
      this.center.lat = this.$refs.bmcity.map.Oe.lat
      this.de_lng = this.$refs.bmcity.map.Oe.lng
      this.de_lat = this.$refs.bmcity.map.Oe.lat
      this.zoom = 12
    },
    dragEndPosition(e) {
      // 拖拽后的marker所在坐标
      this.de_lng = e.point.lng
      this.de_lat = e.point.lat
    },
    getList() {
      this.listLoading = true
      getDangerList(this.listQuery).then(response => {
        this.list = response.data.context.records
        this.total = response.data.context.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作成功',
        type: 'success'
      })
      row.status = status
    },
    resetTemp() {
      this.temp = {
        supervisorid: '',
        supervisorname: '',
        dresname: '',
        drestype: '',
        level: '',
        updatetime: '',
        longitude: '',
        latitude: '',
        levation: '',
        province: '',
        city: '',
        zone: '',
        district: '',
        address: ''
      }
      this.cityOpt=[]
      this.zoneOpt=[]
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      for (const key in this.supervisorOptions) {
        if (this.temp.supervisorid === this.supervisorOptions[key].value) {
          this.temp.supervisorname = this.supervisorOptions[key].label
        }
      }
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addDanger(this.temp).then(response => {
            if (response.data.status === '0') {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: response.data.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '失败',
                message: response.data.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.showDistrict()
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateDanger(tempData).then(response => {
            if (response.data.status === '0') {
              this.dialogFormVisible = false
              this.getList()
              this.$notify({
                title: '成功',
                message: response.data.msg,
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '失败',
                message: response.data.msg,
                duration: 2000
              })
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDanger(row.dresourceid).then(response => {
          if (response.data.status === '0') {
            this.getList()
            this.$notify({
              title: '成功',
              message: response.data.msg,
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify.error({
              title: '失败',
              message: response.data.msg,
              duration: 2000
            })
          }
        })
      })
    },
    querySupervisorOptions() {
      selectLabelValue().then(response => {
        if (response.data.status === '0') {
          this.supervisorOptions = response.data.context
        }
      })
    },
    queryProvinceOpt() {
      getProvinceOpt().then(response => {
        this.provinceOpt = response.data.context
      })
    },
    showDistrict(){
      this.cityOpt = []
      this.zoneOpt = []
      if(this.temp.province == '' || this.temp.province == undefined){
        this.temp.city = ''
        this.temp.zone = ''
      }else if(this.temp.city == '' || this.temp.city == undefined){
        this.temp.province = parseInt(this.temp.province)
        this.temp.zone = ''
        getCityOrZoneOpt(this.temp.province).then(response => {
          this.cityOpt = response.data.context
        })
      }else if(this.temp.zone == '' || this.temp.zone == undefined){
        this.temp.province = parseInt(this.temp.province)
        this.temp.city = parseInt(this.temp.city)
        getCityOrZoneOpt(this.temp.province).then(response => {
          this.cityOpt = response.data.context
        })
        getCityOrZoneOpt(this.temp.city).then(response => {
          this.zoneOpt = response.data.context
        })
      }else{
        // 转成int类型才能回显
        this.temp.province = parseInt(this.temp.province)
        this.temp.city = parseInt(this.temp.city)
        this.temp.zone = parseInt(this.temp.zone)
        // 获取市区选项
        getCityOrZoneOpt(this.temp.province).then(response => {
          this.cityOpt = response.data.context
        })
        getCityOrZoneOpt(this.temp.city).then(response => {
          this.zoneOpt = response.data.context
        })
      }
    },
    chooseProvince() {
      getCityOrZoneOpt(this.temp.province).then(response => {
        this.cityOpt = response.data.context
      })
      this.zoneOpt = []
      this.temp.city = ''
      this.temp.zone = ''
    },
    chooseCity() {
      getCityOrZoneOpt(this.temp.city).then(response => {
        this.zoneOpt = response.data.context
      })
      this.temp.zone = ''
    },
    dformat(fmt, date) {
      return dateFormat(fmt, date)
    }
  }
}
</script>
<style>
  #district{
    margin-bottom: 17px;
  }
  #district div{
    width: 113px;
    display: inline-block;
  }
  #pczlabel{
    padding-left: 45px;
    width: 96px;
    height: 36px;
    display: inline-block;
    font-size: 14px;
    color: #606266;
    font-weight: 700;
  }
  .select-width-100{
    width: 100%;
  }
  #lola div{
    width: 38%;
    display: inline-block;
  }
  /*必须给容器指高度，要不然地图将显示在一个高度为0的容器中，自然看不到*/
  .map {
    width: 100%;
    height: 500px;
  }
  .anchorBL {
    display: none;
  }
  /*.mapDialog{
    width: 50%;
    height: 40%;
  }*/
</style>
